package top.bbman.boot.exception.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.bbman.boot.exception.global.PeaBizException;
import top.bbman.boot.repository.enums.PeaCodeEnum;
import top.bbman.boot.repository.vo.PeaOut;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 全局异常拦截器
 *
 * @author 祥霸
 * @version 1.0.0
 */
@Slf4j
@RestControllerAdvice
@Order(1)
public class PeaGlobalExceptionHandler {

    @ExceptionHandler(PeaBizException.class)
    public PeaOut<String> bizExceptionHandler(HttpServletRequest request, PeaBizException e) {
        log.error("uri: {}, error: {}", request.getRequestURI(), e);
        return PeaOut.build(e.getCode(), e.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public PeaOut<String> bindExceptionHandler(HttpServletRequest request, MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getFieldError();
        log.error("uri: {}, error: {}", request.getRequestURI(), e);
        return PeaOut.build(PeaCodeEnum.PARAMS_BAD.code(), Objects.isNull(objectError)?"" : objectError.getDefaultMessage());
    }

    @ExceptionHandler(Throwable.class)
    public PeaOut<String> exceptionHandler(HttpServletRequest request, Throwable e) {
        log.error("uri: {}, error: {}", request.getRequestURI(), e);
        return PeaOut.build(PeaCodeEnum.ERROR.code(), e.getMessage());
    }


}
